<template>
  <div class="select">
    <van-field
      :label="payload.label"
      :name="payload.labelKey"
      placeholder="请选择"
      readonly
      :required="payload.required"
      :value="value[payload.labelKey]"
      clickable
      :rules="payload.rules"
      @click="showPicker"
    >
      <template #button>
        <slot>
          <van-icon name="arrow" />
        </slot>
      </template>
    </van-field>

    <van-popup v-model="pickerShow" position="bottom" get-container="body">
      <van-datetime-picker
        v-if="payload.type === 'date'"
        v-model="currentDate"
        :type="payload.dateType"
        title="请选择时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onDateConfirm"
        @cancel="onCancel"
      />
      <van-picker
        v-else
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'CSelect',
  props: {
    payload: {
      type: Object,
      default: () => ({
        placeholder: '请选择',
        valueKey: '', // 需要传的字段值
        labelKey: '', // 当前显示字段
        label: '',
        type: 'select', // 支持date
        dateType: 'datetime',
        columns: [],
        rules: [],
      }),
    },
    value: [Object],
  },
  data() {
    return {
      formData: {},
      pickerShow: false,
      pickerType: '',
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2050, 10, 1),
      currentDate: new Date(),
    };
  },
  computed: {
    columns() {
      if (!this.payload.columns || !this.payload.columns.length) return [];
      return this.payload.columns.map(col => ({ ...col, text: col[this.payload.labelKey] }));
    },
    formatDateType() {
      if (this.payload.dateType === 'datetime') {
        return 'YYYY-MM-DD HH:mm:ss';
      }
      return 'YYYY-MM-DD';
    },
  },
  methods: {
    showPicker() {
      this.pickerShow = true;
    },
    onCancel() {
      this.formData[this.payload.labelKey] = '';
      this.formData[this.payload.valueKey] = '';
      this.$emit('input', {
        ...this.value,
        ...this.formData,
      });
      this.pickerShow = false;
    },
    onConfirm(item) {
      if (!item) return;
      this.formData[this.payload.labelKey] = item[this.payload.labelKey] || item.text;
      this.formData[this.payload.valueKey] = item[this.payload.valueKey] || item.value;
      this.$emit('input', {
        ...this.value,
        ...this.formData,
      });
      this.pickerShow = false;
    },
    onDateConfirm(value) {
      this.formData[this.payload.labelKey] = this.$dayjs(value).format(this.formatDateType);
      this.$emit('input', {
        ...this.value,
        ...this.formData,
      });
      this.pickerShow = false;
    },
  },
};
</script>
